import { Request, Response, NextFunction } from 'express';
import { verifyToken } from '../utils/jwt';

export const authMiddleware = (req: Request, res: Response, next: NextFunction) => {
  const authHeader = req.headers.authorization;
  if (!authHeader || !authHeader.startsWith('Bearer ')) {
    return res.status(401).json({ code: 401, message: '未登录', data: null });
  }

  try {
    const token = authHeader.slice(7);
    const user = verifyToken(token);
    (req as any).user = user;
    next();
  } catch (err) {
    return res.status(401).json({ code: 401, message: 'token 无效或过期', data: null });
  }
};
